<template>
  <div class="order-container">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="search-form-wrapper">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="订单编号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" />
          </el-form-item>
          <el-form-item label="订单项标题">
            <el-input v-model="searchForm.itemTitle" placeholder="请输入订单项标题" />
          </el-form-item>
          <el-form-item label="支付状态">
            <el-select v-model="searchForm.paymentStatus" placeholder="全部">
              <el-option label="全部" value="" />
              <el-option label="待支付" value="PENDING" />
              <el-option label="已支付" value="PAID" />
              <el-option label="支付失败" value="FAILED" />
              <el-option label="已退款" value="REFUNDED" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.status" placeholder="全部">
              <el-option label="全部" value="" />
              <el-option label="待处理" value="PENDING" />
              <el-option label="处理中" value="PROCESSING" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-select v-model="searchForm.paymentMethod" placeholder="全部">
              <el-option label="全部" value="" />
              <el-option label="支付宝" value="ALIPAY" />
              <el-option label="微信支付" value="WECHAT" />
              <el-option label="余额支付" value="BALANCE" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list-wrapper">
      <div class="order-list">
        <el-table
          ref="orderTable"
          v-loading="loading"
          :data="orderData"
          style="width: 100%"
          class="order-table"
          empty-text="暂无订单记录"
        >
          <el-table-column prop="id" label="订单ID" width="80" />
          <el-table-column prop="orderNo" label="订单编号" width="180" />
          <el-table-column prop="userId" label="用户ID" width="80" />
          <!-- 移除不存在的订单类型列 -->
          <!-- 移除不存在的关联项ID列 -->
          <el-table-column prop="itemTitle" label="订单项标题" min-width="200" />
          <el-table-column prop="amount" label="应付金额" width="120" align="right">
            <template #default="scope">¥{{ formatAmount(scope.row.amount) }}</template>
          </el-table-column>
          <el-table-column prop="originalAmount" label="原价" width="100" align="right">
            <template #default="scope">¥{{ formatAmount(scope.row.originalAmount) }}</template>
          </el-table-column>
          <el-table-column prop="discountAmount" label="优惠金额" width="100" align="right">
            <template #default="scope">¥{{ formatAmount(scope.row.discountAmount) }}</template>
          </el-table-column>
          <el-table-column prop="paymentStatus" label="支付状态" width="100">
            <template #default="scope">
              <el-tag :type="getPaymentStatusTagType(scope.row.paymentStatus)">
                {{ getPaymentStatusText(scope.row.paymentStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="100">
            <template #default="scope">
              {{ getPaymentMethodText(scope.row.paymentMethod) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" />
          <el-table-column prop="payTime" label="支付时间" width="180" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewOrderDetail(scope.row.id)">
                查看详情
              </el-button>
              <el-button size="small" @click="handleEditOrder(scope.row.id)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页控件 - 修复current-change事件绑定 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { ElTable } from 'element-plus';
import type { Order } from '@/types/Orders';
import { getOrders } from '@/api/order/order';
import type { PageData } from '@/api/types';

const searchForm = reactive({
  orderNo: '',
  itemTitle: '',
  paymentStatus: '',
  status: '',
  paymentMethod: ''
});
// 订单数据
const orderData = ref<Order[]>([]);
const loading = ref(false);
const orderTable = ref<InstanceType<typeof ElTable>>();

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 格式化金额
const formatAmount = (amount: number | null): string => {
  return amount ? amount.toFixed(2) : '0.00';
};

// 加载订单数据 - 修复数据解析路径
const loadOrderData = async () => {
  loading.value = true;
  try {
    const response = await getOrders({
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      // 可以添加其他搜索条件
      ...(searchForm.orderNo && { orderNo: searchForm.orderNo }),
      ...(searchForm.itemTitle && { itemTitle: searchForm.itemTitle }),
      ...(searchForm.paymentStatus && { paymentStatus: searchForm.paymentStatus }),
      ...(searchForm.status && { status: searchForm.status }),
      ...(searchForm.paymentMethod && { paymentMethod: searchForm.paymentMethod })
    });
    
    if (response) {
      console.log(response)
      if (response.success) {
        // 修复数据解析路径
        orderData.value = response.data?.list || [];
        pagination.total = response.data?.total || 0;
      } else {
        ElMessage.error(response.message || '加载订单数据失败');
      }
    } else {
      ElMessage.error('加载订单数据失败：响应数据格式错误');
    }
  } catch (error) {
    ElMessage.error('加载订单数据失败');
    console.error('加载订单数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
  loadOrderData();
};
const resetSearch = () => {
  searchForm.orderNo = '';
  searchForm.itemTitle = '';
  searchForm.paymentStatus = '';
  searchForm.status = '';
  searchForm.paymentMethod = '';
  pagination.currentPage = 1;
  loadOrderData();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadOrderData();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  loadOrderData();
};

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  ElMessage.info(`查看订单 ${orderId} 详情`);
  // 实际项目中这里应该跳转到详情页或打开详情弹窗
};

// 编辑订单
const handleEditOrder = (orderId: number) => {
  ElMessage.info(`编辑订单 ${orderId}`);
  // 实际项目中这里应该打开编辑弹窗或跳转到编辑页面
};

const getPaymentStatusTagType = (status: string | null): string => {
  if (!status) return 'default';
  const statusMap: Record<string, string> = {
    PENDING: 'warning',
    PAID: 'success',
    FAILED: 'danger',
    REFUNDED: 'info'
  };
  return statusMap[status] || 'default';
};

// 获取支付状态文本 - 处理null值
const getPaymentStatusText = (status: string | null): string => {
  if (!status) return '未知';
  const statusMap: Record<string, string> = {
    PENDING: '待支付',
    PAID: '已支付',
    FAILED: '支付失败',
    REFUNDED: '已退款'
  };
  return statusMap[status] || '未知状态';
};

// 获取订单状态标签类型 - 处理null值
const getStatusTagType = (status: string | null): string => {
  if (!status) return 'default';
  const statusMap: Record<string, string> = {
    PENDING: 'warning',
    PROCESSING: 'primary',
    COMPLETED: 'success',
    CANCELLED: 'danger'
  };
  return statusMap[status] || 'default';
};

// 获取订单状态文本 - 处理null值
const getStatusText = (status: string | null): string => {
  if (!status) return '未知';
  const statusMap: Record<string, string> = {
    PENDING: '待处理',
    PROCESSING: '处理中',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 获取支付方式文本 - 处理null值
const getPaymentMethodText = (method: string | null): string => {
  if (!method) return '未知';
  const methodMap: Record<string, string> = {
    ALIPAY: '支付宝',
    WECHAT: '微信支付',
    BALANCE: '余额支付'
  };
  return methodMap[method] || '未知方式';
};

// 初始化加载数据
onMounted(() => {
  loadOrderData();
});
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 80px auto;
  padding: 32px;
  border: 1px solid #eee;
  border-radius: 8px;
  background: #fff;
}
.error {
  color: red;
  margin-top: 12px;
}
</style>